<?php
namespace app\admin\controller;
use think\facade\Db;
use app\admin\model\{SurveyQuestion,SurveyOption,SurveyAnswer,SurveyTheme};

class Survey extends Base{
    

    /**
     * 问卷主题
     * @return void
     * @author Sam
     * date 2021-09-08
     */
    public  function survey_theme(){
        if(IS_POST) {
            $search  = request()->param();
            $where = [];
            $db   = SurveyTheme::where($where)->order('id desc');
            $list = $db->limit(paginator())->select();
            admin_response(0, 'success', $list, $db->count());
        }
        return $this->fetch('index');
    }

    /**
     * 主题添加
     * @return void
     * @author Sam
     * date 2021-09-08
     */
    public function survey_theme_add(){
        if(request()->isPost()) {
            $data = request()->post();
            if(SurveyTheme::create($data)) json_response(1,'操作成功');
            json_response(0,'操作失败');
         }else{
            return $this->render_form([
                ['type'=>'text', 'name'=>'title', 'title'=>'标题', 'lay-verify'=>'required'],
                ['type'=>'text', 'text_type'=>'number','name'=>'sort', 'title'=>'排序'],
            ]);
         }
    }

        /**
     * 主题编辑
     * @return void
     * @author Sam
     * date 2021-09-08
     */
    public function survey_theme_edit(){
        $id = param_check('id');
        if(request()->isPost()) {
            $data = request()->post();
            if(SurveyTheme::update($data,['id'=>$id])) json_response(1,'操作成功');;
            json_response(0,'操作失败');
         }else{
             $data = SurveyTheme::find($id);
            return $this->render_form([
                ['type'=>'text', 'name'=>'title', 'title'=>'标题', 'lay-verify'=>'required'],
                ['type'=>'text', 'text_type'=>'number','name'=>'sort', 'title'=>'排序'],
            ],$data);
         }
    }

    /**
     * 主题删除
     * @return void
     * @author Sam
     * date 2021-09-08
     */
    public function survey_theme_del(){
        $id = param_check('id');
        if(request()->isPost()) {
            $data = SurveyTheme::find($id);
            if($data->delete()) \json_response(1,'操作成功');
            \json_response(0,'操作失败');
         }else{
             $data = SurveyTheme::find($id);
            return $this->render_form([
                ['type'=>'text', 'name'=>'title', 'title'=>'标题', 'lay-verify'=>'required'],
                ['type'=>'text', 'text_type'=>'number','name'=>'sort', 'title'=>'排序'],
            ],$data);
         }
    }
    /**
     * 题目首页
     */
    public function index(){
        if(IS_POST) {
            $search  = request()->param();
            $where = [];
            if(isset($search['title'])&&$search['title'] !=''){
                $where[] = ['title','like',"%{$search['title']}%"];
            } 
            $db   = SurveyQuestion::with('survey')->where($where)->order('id desc');
            $list = $db->limit(paginator())->select();
            if(count($list)){
                foreach($list as $v){
                    $status = [1=>'单选',2=>'多选',3=>'填空',4=>'选择填空'];
                    $v['type_text'] = $status[$v['type']];
                }
            }
            admin_response(0, 'success', $list, $db->count());
        }
    
        return $this->render_table([
           "page"=>true,
            "toolbar" => [
                table_button('admin/Survey/add',"添加","frame")
            ],
            "toolbar_row" => [ 
                    table_button('admin/Survey/edit',"编辑","frame"),
                    table_button('admin/Survey/del',"删除","confirm"),
                   
                    ],
            "cols" => [ 
                     ["type"=>"checkbox"],
                    ["field"=>"id", "title"=>"编号","align"=>"center"],
                    ["field"=>"survey_title", "title"=>"主题","align"=>"center"],
                    ["field"=>"title", "title"=>"标题","align"=>"center"],
                    ["field"=>"type_text", "title"=>"类型","align"=>"center"],

            ],
            "where"=>[
                'title'  => ['type'=>'input', 'title'=>'关键字','placeholder'=>'题目名称搜索'],
            ]

            ],false);

    }

        /**
     * 批量导入
     * @return void
     * @author Sam
     * date 2021-07-02
     */
    public function import(){
        $survey_id = \param_check('id');
        set_time_limit(0);
        if(empty($_FILES['file'])) json_response(0, '请选择文件');
        $data = big_csv_to_array($_FILES['file']['tmp_name']);
        $type_option = ['单选' => 1,'多选' => 2,'填空' => 3, '选择填空' => 4];
        $num = 0;
        foreach ($data as $value) {
            if(!empty($value[0])) {
                 if($value[0] == '' || !isset($value[0])){
                    json_response(0,'标题不得为空');
                }
                if($value[1] == '' || !isset($value[1])){
                    json_response(0,'类型不得为空');
                }
                if(trim($value[1]) == '单选' || trim($value[1]) == '多选' ){
                    //选择题目没有选项报错
                    if(!$value[2] && !$value[3] && !$value[4]&& !$value[5]&& !$value[6]&& !$value[7]){
                        json_response(0,'选择题至少填写一个选项');
                    }
                }
                if(SurveyQuestion::where(['title'=>$value[0]])->count()){
                    continue;
                }
                Db::startTrans();
                try {
                    $survey_question =  SurveyQuestion::create([
                        'survey_id' => $survey_id,
                        'title' => trim((string)$value[0]),
                        'type' => trim((int)$type_option[$value[1]])
                    ]);
                    $insert_data = ['A'=>$value[2],'B'=>$value[3],'C'=>$value[4],'D'=>$value[5],'E'=>$value[6],'F'=>$value[7]];
                    foreach($insert_data as $k=>$v){
                        if(trim($v) != '' && $v){
                            SurveyOption::create([
                                'question_id' => $survey_question->id,
                                'option_name' => $v,
                                'option_number'  => $k 
                            ]);
                        }
                    }
                     $num += 1;
                    Db::commit();
                 } catch (\Exception $e) {
                    Db::rollback();
                    $num = 0;
                    json_response(0,$e->getMessage());
                 }
               
            }
        }
        json_response(1,"成功导入{$num}条数据");
    }

    /**
     * 答题记录
     *
     * @return void
     * @Description
     * @example
     * @author Sam
     * @since 
     */
    public function record(){
           $search  = request()->param();
            $where = [];
            if(isset($search['title']) && $search['title'] !=''){
                $where[] = ['question_name','like',"%{$search['title']}%"];
            }
            if(isset($search['user']) && $search['user'] !=''){
                $ids = User::where('mobile|name','like',"%{$search['user']}%")->column('id');
                if($ids && is_array($ids)){
                    $where[] = ['uid','in',$ids];
                } 
            }
            if(isset($search['is_right']) && $search['is_right'] !=''){
                $where[] = ['is_right','=',$search['is_right']];
            }
        if(IS_POST) {
            $db   = SurveyAnswer::with(['question','user','survey'])->where($where)->order('id desc');
            $list = $db->limit(paginator())->select();
            admin_response(0, 'success', $list, $db->count());
        }

        if(IS_EXCEL) {
            $db = SurveyAnswer::with(['question','user','survey'])->where($where)->order('id asc');
            big_array_to_csv($db, '答题记录', [ 
                'id'                => '编号',
                'name'         => '姓名',
                'question_name'          => '题目',
                'answer_name'     => '答案'
            ]);
        }

        return $this->render_table([
           "page"=>true,
           "export" => true,
            "cols" => [ 
                    ["field"=>"id", "title"=>"编号","align"=>"center"],
                    ["field"=>"survey_title", "title"=>"主题","align"=>"center"],
                    ["field"=>"name", "title"=>"姓名","align"=>"center"],
                    ["field"=>"question_name", "title"=>"问题","align"=>"center"],
                    ["field"=>"answer_name", "title"=>"答案","align"=>"center"],
            ],
            "where"=>[
                'user'  => ['type'=>'input', 'title'=>'用户','placeholder'=>'姓名，手机号搜索'],
                'title'  => ['type'=>'input', 'title'=>'题目','placeholder'=>'题目名称搜索'],
            ]

            ],false);

    }

    /**
     * 下载模板
     *
     * @return void
     * @Description
     * @example
     * @author Sam
     * @since 
     */
    public function down_temp(){
      header("Location:https://game.vrupup.com/resources/sam_base/survey.csv");
      exit();
    }



        /**
     * 添加
     * @return void
     * @author 
     * date 
     */
    public function add(){
        if(request()->isPost()) {
           $postData  = request()->post();
            if($postData['type'] !=3){
                if($postData['type'] == 4 && !in_array('其他',$postData['option_name'])){
                    json_response(0,'选择填空选项必须包含 ‘其他’ ');
                }
                //非填空题
                $option = [];
                if(count(array_filter($postData['option_name'])) != count(array_filter($postData['option_number']))){
                    json_response(0,'请完善选项');
                 }
                if((!count($postData['option_number']) ||!count($postData['option_name']))){
                    json_response(0,'请至少添加一个选项');
                }
                foreach ($postData['option_number'] as $key => $value) {
                    if(!in_array($value,['A','B','C','D','E','F','G','H'])){
                        json_response(0,'选项编号格式仅限A,B,C等');
                    }
                    $option[$value] = $postData['option_name'][$key];
                }
                $postData['option'] = $option;
            }

            if(SurveyQuestion::where('title',$postData['title'])->count()){
                json_response(0,'该题目已存在');
            }
            Db::startTrans();
            try {
               $question =  SurveyQuestion::create([
                    'survey_id' => $postData['survey_id'],
                    'type'      => $postData['type'],
                    'title'     => $postData['title']
                ]);
                if($postData['type'] !=3 && $postData['option']){
                    foreach ($postData['option'] as $key => $value) {
                        SurveyOption::create([
                            'survey_id'   =>$question->survey_id,
                            'question_id' => $question->id,
                            'option_name' => $value,
                            'option_number' => $key
                        ]);
                    }
                }
               Db::commit();
            } catch (\Exception $e) {
               Db::rollback();
               json_response(0,$e->getMessage());
            }
            json_response(1,'添加成功');
        }else{
            $survey = SurveyTheme::field('id,title')->select();
            $this->assign(compact('survey'));
            return $this->fetch();
        }
    }

        /**
     * 删除选项
     * @return void
     * @author Sam
     * date 2021-02-26
     */
    public function del_option(){
        if(request()->isPost()){
            $id       = request()->post('id/d');
            if($option = SurveyOption::get($id)){
                if($option->delete()){
                    json_response(1,'删除成功');
                }else{
                    json_response(0,'删除失败');
                }
            }else{
                json_response(0,'无此选项记录');
            }
        }else{
            json_response(0,'非法请求');
        }
    }

    /**
     * 编辑
     * @return void
     * @author 
     * date 
     */
    public function edit(){
           $id = \param_check('id');
          if(request()->isPost()){
            $postData  = request()->post();
            if($postData['type'] !=3){
                if($postData['type'] == 4 && !in_array('其他',$postData['option_name'])){
                    json_response(0,'选择填空选项必须包含 ‘其他’ ');
                }
                //非填空题
                $option = [];
                if(count($postData['option_name']) != count($postData['option_number'])){
                    json_response(0,'请完善选项');
                }
                if(count(array_filter($postData['option_name'])) != count(array_filter($postData['option_number']))){
                    json_response(0,'请完善选项');
                 }
                foreach ($postData['option_number'] as $key => $value) {
                    if(!in_array($value,['A','B','C','D','E','F','G','H'])){
                        json_response(0,'选项编号格式仅限A,B,C等');
                    }
                    $option[$value] = $postData['option_name'][$key];
                }
                $postData['option'] = $option;
            }
    
            Db::startTrans();
            try {
                 if(!$question = SurveyQuestion::get($id)) return JsonService::fail('无此题目');
                $question->save($postData);
                if($postData['type'] !=3 && $postData['option']){
                    foreach ($postData['option'] as $key => $value) {
                        if($option = SurveyOption::where('question_id',$id)->where('option_number',$key)->find()){
                            $option->option_name = $value;
                            $option->option_number = $key;
                            $option->save();
                        }else{
                            SurveyOption::create([
                                'question_id' => $question->id,
                                'option_name' => $value,
                                'option_number' => $key
                            ]);
                        }
                      
                    }
                }
               Db::commit();
            } catch (\Exception $e) {
               Db::rollback();
               json_response(0,$e->getMessage());
            }
            return json_response(1,'编辑成功');
        }else{
             if(!$id) json_response('缺少ID');
             if(!$info = SurveyQuestion::get($id)) json_response(0,'无此信息');
             $this->assign('info',$info);
             return $this->fetch();
        }
    }





        /**
     * 删除
     * @return void
     * @author Sam
     * date 2021-07-01
     */
    public function del(){
        $id = param_check('id');
        if(!$SurveyModel = SurveyQuestion::get($id)) json_response(0,'不存在');
        if($SurveyModel->delete()){
            SurveyOption::where('question_id',$id)->delete();
            json_response(1,'操作成功');
        } 
        json_response(0,'操作失败');
    }

}